<template>
	<view class="login">
		
		
		<view class="login-logo">
			<image class="logo" src="https://storage.longdiankj.com/prod-api/profile/avatar/2025/02/05/3.png" ></image>
			<view class="title">龙殿仓库</view>
		</view>
		
		<view class="wx-btn" >
			<button v-if="!userPhone" open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber" class="btn">
				手机号一键登录
			</button>
			
			<!-- 如果本地已经有了userPhone,  登陆过 -->
			<button v-if="userPhone" @tap="login"  class="btn">
				手机号一键登录
			</button>
		</view>
		
		<view class="link-area">	  		  
		  	<text class="link"> 登录后可使用更多功能</text>	  
		</view>
				
		<!-- <view  @tap="agree">
			<text> 同意获取用户信息 </text>
		</view> -->
		
	</view>
</template>

<script>
	import * as api from '../../utils/api.js'
	export default {
		name:"login",
		data() {
			return {
				userCheck: false,
				wxLoginDisabled: true,
				code: '',
				userInfo: {},
				userPhone: '',
				userType: 3, // 自然流量
				drainageUserId: '',
				codeId: '',
				codeInfo: '',
			}
		},
		
		onLoad(options){
			this.userPhone = uni.getStorageSync('userPhone') || '';
			// const scene = decodeURIComponent(options.scene);
			// const params = {};
			// const pairs = scene.split('&');
			// for (let i = 0; i < pairs.length; i++) {
			// 	const pair = pairs[i].split('=');
			// 	params[pair[0]] = pair[1];
			// }
			// const {userId,  codeId, type} = params;
		  //   this.drainageUserId = userId;
			// this.codeId = codeId;

	    //     console.log('login-onLoad：', params);
			// if (type) {
			// 	this.userType = type;
			// 	return;
			// }
			this.codeInfo = options.scene;
			console.log('login-codeInfo：', options.scene);
			
		},
		methods: {
			async bindUserSource() {
				const params = {userType: this.userType};
				if (this.userType == 1) {
					params.drainageUserId = this.drainageUserId;
				}
				if (this.userType == 2) {
					params.codeId = this.codeId;
				}
				// api.bindUserSource(params);
			},
			async getDictTypeMap (dictType) {
				const res = await api.dictTypeInfo(dictType);
				const dict = res.data || [];
				uni.setStorageSync(dictType, JSON.stringify(dict))
			},
			async onGetPhoneNumber(e) {

			    try {				
			      // 1. 调用 wx.login 获取临时登录凭证 code
			      const wxLoginRes = await new Promise((resolve, reject) => {
			        wx.login({
			          success: res => resolve(res),
			          fail: err => reject(err)
			        });
			      });
                
			      const { encryptedData, iv, code } = e.detail;
			      if (!encryptedData ||!iv) {
			        console.error('用户拒绝授权或数据获取失败');
			        return;
			      }
			      // 将 code、encryptedData 和 iv 发送给后端 -- 这个code 是getphonenumber 的code 不是wx.login 返回值的code
			      const res = await api.getUserPhone({ code })
			      if (res.code == 200) {
					this.userPhone = res.user_phone;
			        // console.log('获取手机号成功:'+ res.user_phone);
					// 接下来做用户登录
					const loginRes = await api.minLogin({
						 code: wxLoginRes.code,  
						 userPhone: res.user_phone,
						 codeInfo: this.codeInfo
						});
					const token = loginRes.token;
					
					uni.setStorageSync('token', token);
					uni.setStorageSync('userPhone', this.userPhone);
					
					uni.switchTab({
					  url: '/pages/index/index'
					});
					
					this.getDictTypeMap('relic_status');
					this.getDictTypeMap('take_status');
					
			      } else {
			        console.error('获取手机号失败:', res.message);
			      }
			    } catch (error) {
			      console.error('获取手机号过程中出现错误:', error);
			    }
			  },
			async login () {
				// 1. 调用 wx.login 获取临时登录凭证 code
				const wxLoginRes = await new Promise((resolve, reject) => {
				  wx.login({
				    success: res => resolve(res),
				    fail: err => reject(err)
				  });
				});
				// 接下来做用户登录
				const loginRes = await api.minLogin({ 
					code: wxLoginRes.code,  
					userPhone: this.userPhone,
					codeInfo: this.codeInfo 
				});
				const token = loginRes.token;
	
				uni.setStorageSync('token', token);
				uni.setStorageSync('userPhone', this.userPhone);
				
				uni.switchTab({
				  url: '/pages/index/index'
				});	
				this.getDictTypeMap('relic_status');
				this.getDictTypeMap('take_status');

			},
			agree () {
				// 调用 wx.login 获取登录凭证 code
				      wx.login({
				        success: (res) => {
				          if (res.code) {
							console.log('res.code=' +  res.code)
							 this.code = res.code
				             this.wxLoginDisabled = true
				          } else {
				            console.log('获取登录凭证失败:', res.errMsg);
				          }
				        },
				        fail: (err) => {
				          console.log('登录失败:', err);
				        }
				      });
		
			},
			getUserInfo() {
				// 调用 wx.getUserProfile 获取用户信息
				wx.getUserProfile({
				  desc: '用于完善用户信息',
				  success: (userRes) => {
					  console.log('用户信息', userRes);
				  },
				  fail: (err) => {
				    console.log('获取用户信息失败:', err);
				  }
				});
			}
		}
	}
</script>

<style lang="scss">
	.login {
		color: white;
		.login-logo {
			margin: 180rpx 0 80rpx 0;
			text-align: center;
			.logo {
				width: 300rpx;
				height: 300rpx;
			}
			.title {
				font-size: 24rpx;
				color: white;
			}
		}
		.wx-btn {
			
			   width: 400rpx;
			   margin: 40rpx auto;
			   box-sizing: border-box;
			   font-size: 42rpx;
			   text-align: center;
			   .btn {
				   background: green;
				   color: white;
				   border-radius: 20rpx;
			   }
		}
		.disabled {
			   background:  darkgrey;
		}
	}
	
	.link-area {
		display: flex;
		justify-content: center;
		font-size: 28rpx;
	}
	.link {
		color: #fff;
	}

</style>